<template>
  <!-- 新增编辑查看弹出框 -->
  <el-dialog :title="dialogTitle" v-model="editVisible" width="30%" :close-on-click-modal="closeOnClickModal" draggable @closed="closedFormDialog">
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="20">
          <el-form-item label="业务员手机号：" prop="user_id">
            <el-select v-model="form.user_id" filterable remote placeholder="请输入业务员手机号" :remote-method="debounceHandleGetStoreUserInfo" :loading="userLoading" @change="handleChangeStoreUser">
              <el-option v-for="item in storeUseList" :key="item.user_id" :label="form.mobile + item.user_name" :value="item.user_id"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="20">
          <el-form-item label="业务员名称：" prop="username">
            <el-input v-model.trim="form.username" disabled placeholder="业务员名称"> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="formStatus = 'none'">取 消</el-button>
        <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { postOrPutType } from "@/constants";
import type { ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import { getStoreUserInfo } from "@/utils/api/storeUser";
import type { ISearchStoreUser, IStoreUser } from "@/types/staff/storeUser";
import { debounce } from "@/utils/utils";
import { commonStaffInfo } from "@/utils/api/staff";
import type { IStaff } from "@/types/staff/staff";
const { disabledbtn, loading, toggleState } = useState();
const emit = defineEmits<{
  handleSuccess: [];
}>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const form = defineModel<IStaff>("form", { required: true });

const editVisible = ref(false);
const formRef = useTemplateRef("formRef");

const rules = reactive({
  user_id: [{ required: true, message: "请输入选择业务员手机号", trigger: "blur" }]
});

const dialogTitle = ref("新增");
const userLoading = ref(false);
const storeUseList = ref<Array<IStoreUser>>([]);
const methodType = ref<postOrPutType>("POST");
const usernameDisabled = ref(false);
const closeOnClickModal = ref(false);
const isDisabledbtn = ref(false);

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    dialogTitle.value = "查看";
    editVisible.value = true;
    isDisabledbtn.value = true;
    closeOnClickModal.value = true;
  },
  edit: () => {
    dialogTitle.value = "编辑";
    methodType.value = "PUT";
    editVisible.value = true;
    usernameDisabled.value = false;
  },
  add: () => {
    dialogTitle.value = "新增";
    methodType.value = "POST";
    editVisible.value = true;
    usernameDisabled.value = false;
  },
  none: () => {
    dialogTitle.value = "新增";
    methodType.value = "POST";
    editVisible.value = false;
    usernameDisabled.value = false;
    isDisabledbtn.value = false;
    closeOnClickModal.value = false;
    form.value.id = 0;
    storeUseList.value = [];
    formRef.value?.resetFields();
    formRef.value?.clearValidate();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});

const debounceHandleGetStoreUserInfo = debounce(handleGetStoreUserInfo, 1000);

// 关闭模态框
function closedFormDialog() {
  changeFormStatus("none");
}
// 切换formStatus
function changeFormStatus(state: ViewMode) {
  formStatus.value = state;
}

/* 获取 店铺（营业员）数据 */
function handleGetStoreUserInfo(...args: unknown[]) {
  const mobile = args[0] as string;
  if (!mobile) return;
  form.value.mobile = mobile;
  storeUseList.value = [];
  userLoading.value = true;
  getStoreUserInfo<Array<IStoreUser>, ISearchStoreUser>({ mobile })
    .then(res => {
      storeUseList.value = res.result;
    })
    .catch(() => {})
    .finally(() => {
      userLoading.value = false;
    });
}

/* 选择店铺（业务员员） */
function handleChangeStoreUser(user_id: number) {
  const data = storeUseList.value.find((item: IStoreUser) => item.user_id == user_id);
  if (data) {
    form.value.username = data.user_name;
  }
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  toggleState(true);
  commonStaffInfo(form.value, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      changeFormStatus("none");
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
</script>

<style lang="scss" scoped></style>
